<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class Gift extends Base
{
    protected $table = 'gift_library';
    protected $mall_table = 'mall_goods';
    protected $stream_table = 'gift_stream';
    protected $cache_week_gift_info = "WEEK:GIFT:LIBRARY:INFO";
    protected $cache_week_gift_wealth = "WEEK:GIFT:LIBRARY:WEALTH";//财富
    protected $cache_week_gift_active = "WEEK:GIFT:LIBRARY:ACTIVE";//
    protected $cacheLightsList = "CARD:GET:GIFT:LIST";//
    protected $cacheAllGiftsList = "CARD:ALL:LIGHTS:GIFT:LIST";//

    CONST CACHE_STAND_FOR_ELECTION = "CACHE:STAND_FOR_ELECTION";
    CONST CACHE_NO_STAND_FOR_ELECTION = "CACHE:NO:STAND_FOR_ELECTION";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getGiftInfo($gift_id)
    {
        $where['gift_id'] = $gift_id;
        $data = DB::connection("mysql_kkaudio")
            ->table($this->table)
            ->where($where)
            ->first();
        $data = self::objToArray($data);
        $data['image'] = build_image($data['image']);
        return $data;
    }

    public function getGiftInfoToIds($gift_ids = [])
    {
        $data = DB::connection("mysql_kkaudio")
            ->table($this->table)
            ->whereIn('gift_id', $gift_ids)
            ->get();
        $data = self::objToArray($data);
        foreach ($data as &$v) {
            $v['image'] = build_image($v['image']);
        }
        return $data;
    }

    public function getGiftCache($gift_id)
    {

        $cache = Redis::HGET($this->cache_gift_info, $gift_id);
        do {
            if ($cache) {
                break;
            }
            $where['gift_id'] = $gift_id;
            $data = DB::connection("mysql_kkaudio")
                ->table($this->table)
                ->where($where)
                ->select('gift_id', 'price')
                ->first();
            $res = self::objToArray($data);
            Redis::HSET($this->cache_gift_info, $gift_id, $res['price']);
            $cache = Redis::HGET($this->cache_gift_info, $gift_id);
        } while (false);
        return $cache;
    }

    public function getGiftCacheExpire($gift_id)
    {
        $cache = Redis::HGET($this->cache_week_gift_info, $gift_id);
        do {
            if ($cache) {
                break;
            }
            $where['gift_id'] = $gift_id;
            $data = DB::connection("mysql_kkaudio")
                ->table($this->table)
                ->where($where)
                ->select('gift_id', 'price')
                ->first();
            $res = self::objToArray($data);
            Redis::HSET($this->cache_week_gift_info, $gift_id, $res['price']);
            $cache = Redis::HGET($this->cache_week_gift_info, $gift_id);
            Redis::expire($this->cache_week_gift_info, 86400);
        } while (false);
        return $cache;
    }

    public function getPkGift($room_ids = [], $start_time, $end_time)
    {
        $times = [$start_time, $end_time];
//        $where['type'] = 1;
        $data = DB::connection('mysql_kkaudio')->table($this->stream_table)->whereIn('room_id', $room_ids)->whereBetween('change_timestamp', $times)->get();
        return self::objToArray($data);
    }

    /**
     * 是否是联赛票
     *
     * @param integer $gift_id
     * @return boolean
     */
    public function isFiveLeague($gift_id = 0)
    {
        return DB::connection("mysql_kkaudio")
            ->table($this->table)
            ->where('gift_id', $gift_id)
            ->where('name', '联赛票')
            ->count();
    }

    /**
     * 下一轮选手
     *
     * @param [type] $user_id
     * @return void
     */
    public function standForElection($user_id)
    {
        return Redis::SADD(self::CACHE_STAND_FOR_ELECTION, $user_id);
    }

    /**
     * 清空选手
     *
     * @return void
     */
    public function emptyStandForElection()
    {
        return Redis::del(self::CACHE_STAND_FOR_ELECTION);
    }

    /**
     * 复活赛参赛选手
     *
     * @param [type] $user_id
     * @return void
     */
    public function addLoser($user_id)
    {
        return Redis::SADD(self::CACHE_NO_STAND_FOR_ELECTION, $user_id);
    }

    /**
     * 获取胜出者
     *
     * @return void
     */
    public function getStandForElection()
    {
        return Redis::SMEMBERS(self::CACHE_STAND_FOR_ELECTION);
    }

    /**
     * 是否是胜出者
     *
     * @param [type] $user_id
     * @return boolean
     */
    public function isStandForElection($user_id)
    {
        return (bool)Redis::SISMEMBER(self::CACHE_STAND_FOR_ELECTION, $user_id);
    }

    public function isLoser($user_id)
    {
        return (bool)Redis::SISMEMBER(self::CACHE_NO_STAND_FOR_ELECTION, $user_id);
    }

    public function getGiftInfoCache($gift_id)
    {
        $key = "GIFT:CACHE" . '-' . $gift_id;
        $gift = Redis::GET($key);
        if (!$gift) {
            $where['gift_id'] = $gift_id;
            $data = DB::connection("mysql_kkaudio")
                ->table($this->table)
                ->where($where)
                ->first();
            $data = self::objToArray($data);
            $data['image'] = build_image($data['image']);
            Redis::SET($key, json_encode($data), 'EX', 200);
        }
        return Redis::GET($key);

    }

    public function getGiftInfoCacheToArr($gift_id)
    {
        $key = "GIFT:CACHE" . '-' . $gift_id;
        $gift = Redis::GET($key);
        if (!$gift) {
            $where['gift_id'] = $gift_id;
            $data = DB::connection("mysql_kkaudio")
                ->table($this->table)
                ->where($where)
                ->first();
            $data = self::objToArray($data);
            $data['image'] = build_image($data['image']);
            Redis::SET($key, json_encode($data), 'EX', 200);
        }
        $res = Redis::GET($key);
        return json_decode($res, true);
    }

    public function getMallInfoCache($gift_id)
    {
        $key = "MALL:CACHE" . '-' . $gift_id;
        $gift = Redis::GET($key);
        if (!$gift) {
            $where['goods_id'] = $gift_id;
            $data = DB::connection("mysql_kkaudio")
                ->table($this->mall_table)
                ->where($where)
                ->first();
            $data = self::objToArray($data);
            $data['small_img'] = build_image($data['small_img']);
            Redis::SET($key, json_encode($data), 'EX', 200);
        }
        return json_decode(Redis::GET($key), true);
    }

    public function getPropInfoCache($prop_id)
    {
        $key = "PROP:CACHE" . '-' . $prop_id;
        $gift = Redis::GET($key);
        if (!$gift) {
            $where['prop_id'] = $prop_id;
            $data = DB::connection("mysql_kkaudio")
                ->table('prop')
                ->where($where)
                ->first();
            $data = self::objToArray($data);
            $data['image'] = build_image($data['data_image']);
            Redis::SET($key, json_encode($data), 'EX', 200);
        }
        return Redis::GET($key);
    }


    //获取用户获得礼物id
    public function getUserGiftStream($user_id)
    {
        $key = $this->cacheLightsList . '-' . $user_id;
        $res = Redis::GET($key);
        if (!$res) {
            $where['user_id'] = $user_id;
            $data = DB::connection('mysql_kkaudio')
                ->table('gift_stream')
                ->where($where)
                ->groupBy('gift_id')
                ->get('gift_id');
            $data = self::objToArray($data);
            $gift_ids = array_column($data, 'gift_id');
            if ($gift_ids) {
                $gift_ids = implode(',', $gift_ids);
                Redis::SET($key, $gift_ids, 'EX', 60);
            }
            $res = Redis::GET($key);
        }
        return $res;
    }

    //获取已点亮礼物
    public function getLightsGift($user_id)
    {
        $key = $this->cacheLightsList . '-' . $user_id;
        $giftIds = Redis::GET($key);
        if (!$giftIds) {
            $this->getUserGiftStream($user_id);
            $giftIds = Redis::GET($key);
        }
        //查询已点亮礼物
        $table = 'light_up_card_used';
        $where['user_id'] = $user_id;
        $data = DB::connection('mysql_kkaudio')
            ->table($table)
            ->where($where)
            ->get('gift_id');
        $data = self::objToArray($data);
        if ($data) {
            $lightGiftIds = array_column($data, 'gift_id');
            $lightGiftIds = implode(',', $lightGiftIds);
            $giftIds = $giftIds . ',' . $lightGiftIds;
        }
        return $giftIds;
    }

    /*
     * 获取所有未获取礼物信息
     * @param [$gift_ids] array
     * */
    public function getAllGiftInfo($user_id, $gift_ids = [])
    {
        $key = $this->cacheAllGiftsList . ':' . $user_id;
        $res = Redis::GET($key);
        if (!$res) {
            $where['is_show'] = 1;
            $data = DB::connection('mysql_kkaudio')
                ->table($this->table)
                ->where($where)
                ->whereNotIn('gift_id', $gift_ids)
                ->groupBy('gift_id')
                ->get(['gift_id', 'price', 'name', 'image']);
            $data = self::objToArray($data);
            Redis::SET($key, json_encode($data), 'EX', 60);
            $res = Redis::GET($key);
        }
        return $res;
    }

    public function getAllGiftList($show = 1)
    {
        $key = 'CARD:ALL:GIFT:LIST';
        $res = Redis::GET($key);
        if (!$res) {
            $where = [];
            if ($show != 3) {
                $where['is_show'] = $show;
            }
            $data = DB::connection('mysql_kkaudio')
                ->table($this->table)
                ->where($where)
                ->groupBy('gift_id')
                ->get(['gift_id', 'price', 'name', 'image']);
            $data = self::objToArray($data);
            Redis::SET($key, json_encode($data), 'EX', 180);
            $res = Redis::GET($key);
        }
        return $res;
    }


    public function delLightCache($user_id)
    {
        $key = $this->cacheLightsList . '-' . $user_id;
        $giftKey = $this->cacheAllGiftsList . ':' . $user_id;
        Redis::DEL($giftKey);
        return Redis::DEL($key);
    }


    public function getGiftStreamNum($user_id, $gift_id, $start_time, $price = 0)
    {
        $change_time[] = $start_time;
        $change_time[] = strtotime(date('Y-m-d 23:59:59'));
        $data = DB::connection('mysql_kkaudio')
            ->table($this->stream_table)
            ->where('from_user_id', $user_id)
            ->where('gift_price', '>=', $price)
            ->whereIn('gift_id', $gift_id)
            ->whereBetween('change_timestamp', $change_time)
            ->sum('gift_num');
        return $data;
    }

    public function getGiftStreamCount($user_id, $start_time, $price = 0)
    {
        $change_time[] = $start_time;
        $change_time[] = strtotime(date('Y-m-d 23:59:59'));
        $data = DB::connection('mysql_kkaudio')
            ->table($this->stream_table)
            ->where('from_user_id', $user_id)
            ->where('gift_price', '>=', $price)
            ->whereBetween('change_timestamp', $change_time)
            ->limit(1)
            ->get();
        return self::objToArray($data);
    }
}
